<template>
  <div id="detail">
    <detail-nav-bar class="detail-nav" @titleClick="titleClick" ref="nav"></detail-nav-bar>
    <scroll class="content"
            ref="scroll"
            @scroll="contentScroll"
            :probe-type="3">
      <detail-swiper :top-images="topImages"></detail-swiper>
      <detail-base-info :goods="goods"></detail-base-info>
      <detail-shop-info :shop="shop"></detail-shop-info>
      <detail-goods-info :detail-info="detailInfo" @imageLoad="imageLoad"></detail-goods-info>
      <detail-param-info ref="params" :param-info="paramInfo"></detail-param-info>
      <detail-comment-info ref="comment" :comment-info="commentInfo"></detail-comment-info>
      <good-list ref="recommend" :goods="recommends"></good-list>
    </scroll>
    <detail-bottom-bar @addCart="addToCart"></detail-bottom-bar>

    <back-top @click.native="backClick" v-show="isShowBackTop"></back-top>


<!--    <toast :message="message" :show="show"></toast>-->
  </div>
</template>

<script>
import DetailNavBar from "@/views/detail/childComps/DetailNavBar";
import DetailSwiper from "@/views/detail/childComps/DetailSwiper";
import DetailBaseInfo from "@/views/detail/childComps/DetailBaseInfo";
import DetailShopInfo from "@/views/detail/childComps/DetailShopInfo";
import DetailGoodsInfo from "@/views/detail/childComps/DetailGoodsInfo";
import DetailParamInfo from "@/views/detail/childComps/DetailParamInfo";
import DetailCommentInfo from "@/views/detail/childComps/DetailCommentInfo";
import DetailBottomBar from "@/views/detail/childComps/DetailBottomBar";


import Scroll from "@/components/common/scroll/Scroll";
import GoodList from "@/components/content/goods/GoodList";
import BackTop from "@/components/content/backTop/BackTop";

import {getDetail, Goods, Shop, GoodsParam, getRecommend} from "@/network/detail";
import {debounce} from "@/common/utils";
import {itemListenerMixin} from "@/common/mixin";

import {mapActions} from 'vuex'

// import Toast from "@/components/common/toast/Toast";


export default {
  name: "Detail",
  components: {
    DetailNavBar,
    DetailSwiper,
    DetailBaseInfo,
    DetailShopInfo,
    Scroll,
    DetailGoodsInfo,
    DetailParamInfo,
    DetailCommentInfo,
    GoodList,
    DetailBottomBar,
    BackTop,
    // Toast,
  },
  mixins: [itemListenerMixin],
  data() {
    return {
      iid: null,
      topImages: null,
      goods: {},
      shop: {},
      detailInfo: {},
      paramInfo: {},
      commentInfo: {},
      recommends: [],
      themeTopYs: [],
      getThemeTopY: null,
      currentIndex: 0,
      isShowBackTop: false,
      // message: '',
      // show: false,
    }
  },
  created() {
    //1.保存传入的iid
    this.iid = this.$route.params.iid

    //2.根据iid请求详情数据
    getDetail(this.iid).then(res => {
      //1.获取数据
      const data = res.result;
      // console.log(res);

      //2.获取顶部的轮播图数据
      this.topImages = data.itemInfo.topImages;

      //3.获取商品信息
      this.goods = new Goods(data.itemInfo, data.columns, data.shopInfo.services);

      //4.创建店铺信息
      this.shop = new Shop(data.shopInfo);

      //5.获取商品详细信息
      this.detailInfo = data.detailInfo;

      //6.获取参数信息
      this.paramInfo = new GoodsParam(data.itemParams.info, data.itemParams.rule);

      //7.获取评论信息
      if (data.rate.Crate !== 0) {
        this.commentInfo = data.rate.list[0]
      }


      // this.$nextTick(() => {
      //对应的DOM已经被渲染出来了，但是图片并为加载完成
      //此时获取的offsetTop并不包括图片
      //offsetTop值不对的时候，都是图片的问题

      // this.themeTopYs = []
      //
      // this.themeTopYs.push(0);
      // this.themeTopYs.push(this.$refs.params.$el.offsetTop);
      // this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      // this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      //
      // console.log(this.themeTopYs);
      // });

    })

    //3.请求推荐数据
    getRecommend().then(res => {
      this.recommends = res.data.list
    })

    //4.给getThemeTopY赋值（对getThemeTopY赋值操作进行防抖）  防抖提高性能
    this.getThemeTopY = debounce(() => {
      this.themeTopYs = []
      this.themeTopYs.push(0);
      this.themeTopYs.push(this.$refs.params.$el.offsetTop);
      this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);
      this.themeTopYs.push(Number.MAX_VALUE);

      // console.log(this.themeTopYs);
    }, 100)
  },
  methods: {
    ...mapActions(['addCart']),
    imageLoad() {
      // this.$refs.scroll.refresh();
      this.refresh();
      this.getThemeTopY();

      //不用 this.getThemeTopY()也可以(用以下代码)
      // this.themeTopYs = []
      // this.themeTopYs.push(0);
      // this.themeTopYs.push(this.$refs.params.$el.offsetTop);
      // this.themeTopYs.push(this.$refs.comment.$el.offsetTop);
      // this.themeTopYs.push(this.$refs.recommend.$el.offsetTop);

      // console.log(this.themeTopYs);


    },
    titleClick(index) {
      // console.log(index);
      this.$refs.scroll.scrollTo(0, -this.themeTopYs[index], 500);
    },
    contentScroll(position) {
      //1.获取y值
      const positionY = -position.y

      //2.将 positionY 的值和主体里面的值进行对比
      //[0, 15782, 16677, 16872]
      //Number.Max_VALUE
      //   positionY 在 0 和 15782 之间，  index = 0
      //   positionY 在 15782和 16677 之间， index = 1
      //   positionY 在16677 和 16872 之间， index = 2
      //   positionY 大于等于 16872 ， index = 3
      let length = this.themeTopYs.length
      for (let i = 0; i < this.themeTopYs.length - 1; i++) {

        // if (this.currentIndex !== i && ((i < length - 1 && (positionY >= this.themeTopYs[i]
        //   && positionY < this.themeTopYs[i + 1])) || (i === length - 1) &&
        //   (positionY >= this.themeTopYs[i]))) {
        //   this.currentIndex = i;
        //   // console.log(this.currentIndex);
        //   this.$refs.nav.currentIndex = this.currentIndex;
        // }

        //条件 1
        // this.currentIndex !== i  防止赋值过于频繁
        //条件 2.1 (i < length - 1 && (positionY >= this.themeTopYs[i] && positionY < this.themeTopYs[i + 1]))
        // 判断区间； 在 0 和某个数字之间(i < length - 1)
        //条件 2.2 (i === length - 1) && (positionY >= this.themeTopYs[i])
        // 判断大于等于 i === length - 1


        if (this.currentIndex !== i && (positionY >= this.themeTopYs[i] &&
          positionY < this.themeTopYs[i + 1])) {
          this.currentIndex = i;
          this.$refs.nav.currentIndex = this.currentIndex;
        }

      }

      //3.是否显示回到顶部
      //1.判断BackTop是否显示
      this.isShowBackTop = (-position.y) > 1000;
    },
    backClick() {
      //运用ref="scroll"   访问scroll组件
      // this.$refs.scroll.scroll.scrollTo(0,0,3000);
      this.$refs.scroll.scrollTo(0, 0, 1000)
    },
    addToCart() {
      // 1.获取购物车需要展示的信息
      const product = {}
      product.image = this.topImages[0];
      product.title = this.goods.title;
      product.desc = this.goods.desc;
      product.price = this.goods.realPrice;
      product.iid = this.iid;

      //2.将商品添加到购物车里
      // this.$store.commit('addCart',product)
      // this.$store.dispatch('addCart',product).then(res => {
      //   console.log(res);
      // })

      this.addCart(product).then(res => {
        // console.log(res);
        // this.show = true;
        // this.message = res;
        //
        // setTimeout( () => {
        //   this.show = false;
        //   this.message = '';
        // },1500)

        this.$toast.show(res, 2000);
      })

    },
  },
  mounted() {
    // let refresh = debounce(this.$refs.scroll.refresh, 200)
    // this.itemImageLoad = () => {
    //   refresh()
    // }
    // this.$bus.$on('itemImageLoad', this.itemImageLoad)
  },
  destroyed() {
    this.$bus.$off('itemImageLoad', this.itemImageLoad);
  }
}


</script>

<style scoped>
#detail {
  position: relative;
  z-index: 9;
  height: 100vh;
  background-color: #ffffff;
}

.detail-nav {
  position: relative;
  z-index: 9;
  background-color: #fff;
}

.content {
  height: calc(100% - 44px - 49px);
}
</style>
